<template>
  <div class="warpper">

    <div class="form" @click="isgoprolist = false">
      <el-form ref="ruleForm" :model="formData" size="mini" label-width="160px" style="width:85%">
        <el-row :gutter="20" v-if="isEdit">
          <el-col :span="11">
            <el-form-item label="status" prop="status" style="width: 460px;">
              <template slot-scope="scope">
                <span>{{ formData.status }}</span>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="11" style="text-align: right;">
            <el-form-item>
              <template slot-scope="scope">
                <el-button plain type="primary" v-permission="['saleorders.update']" @click="godisable(true)"
                  :disabled="isapproved"
                  v-if="formData.status =='pending' || formData.status =='rejection'">{{isdiable?"Edit":"Cancel Edit"}}</el-button>
                <el-button plain type="default" v-permission="['saleorders.void']" @click="editstatus(id, 'voided')"
                  :disabled="isapproved" v-if="formData.status =='pending' && isdiable">Voided</el-button>
                <el-button plain type="danger" v-permission="['saleorders.rejection']"
                  @click="editstatus(id, 'rejection')" :disabled="isapproved"
                  v-if="formData.status =='pending' && isdiable">Rejection</el-button>
                <el-button plain type="primary" v-permission="['saleorders.auditing']"
                  @click="editstatus(id, 'approved')" :disabled="isapproved"
                  v-if="formData.status =='pending' && isdiable">Auditing</el-button>

                <el-button plain type="default" @click="goinvocie()"
                  v-if="formData.status =='approved'">invoice</el-button>
                <el-button plain type="default" @click="close()"
                  v-if="formData.status =='approved' || formData.status =='voided' || formData.status =='rejection'">Back</el-button>
              </template>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>


    <div class="form" id="cadd" @click="isgoprolist = false">

      <el-form ref="ruleForm" :model="formData" :rules="rules" size="mini" label-width="164px" style="width:95%"
        :disabled="isdiable">

        <el-row :gutter="20">

          <el-col :span="7">
            <el-form-item label="Customer Name" prop="customer_id" style="width: 460px;">
              <el-select v-model="formData.customer_id" placeholder="Select Customer" style="width:290px;"
                @change="changeterm" filterable remote :remote-method="remoteMethod">
                <el-option v-for="item in customers" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">

            <el-form-item label="Customer ID" prop="customer_id" style="width: 460px;">
              <el-select @change="changeterm" v-model="formData.customer_id" placeholder="Select Customerid"
                style="width:290px;" filterable remote :remote-method="remoteidMethod">
                <el-option v-for="item in customers" :key="item.id" :label="item.customerid" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="Delivery Date" prop="delivery_at" style="width:460px">
              <el-date-picker v-model="formData.delivery_at" type="date" style="width:290px;" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="Dedicated sales staff" prop="staff" style="width: 460px;">
              <el-select v-model="formData.staff" placeholder="Select Staff" style="width:290px;">
                <el-option v-for="item in staff" :key="item.id" :label="item.name" :value="item.name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="Customer credit" prop="customercredit" style="width:460px">
              <el-input v-model="formData.customercredit" style="width:290px;" />
            </el-form-item>
            <!--<el-form-item label="Warehouse" prop="warehouse_id" style="width: 460px;">
              <el-select v-model="formData.warehouse_id" placeholder="Select Warehouse" style="width:300px">
                <el-option v-for="item in warehouse" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item> -->
          </el-col>
          <el-col :span="7">
            <el-form-item label="Remark" prop="remark">
              <el-input :rows="1" type="textarea" v-model="formData.remark" style="width: 290px;"></el-input>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="Currency" prop="currency" style="width: 460px;">
              <el-select v-model="formData.currency" placeholder="Select Currency" style="width:290px;">
                <el-option v-for="item in currency" :key="item.id" :label="item.name" :value="item.name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <!--            <el-form-item label="Order Number" prop="ordernumber" style="width:460px">
              <el-input v-model="formData.ordernumber" disabled />
            </el-form-item> -->
            <el-form-item label="Rate" prop="rate" style="width: 460px;">
              <el-input v-model="formData.rate" style="width:290px;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="Reminder Date" prop="created_at" style="width:460px">
              <el-date-picker v-model="formData.remindertime" type="date" style="width:290px" value-format="yyyy-MM-dd"
                @input="handleremindertimeChange">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">

          <el-col :span="7">
            <el-form-item label="Credit Term" prop="creditterm" style="width: 460px;">
              <el-input v-model="formData.creditterm" style="width:290px;"></el-input>
            </el-form-item>
          </el-col>

          <!--            <el-form-item label="Customer Name" prop="customer_id" style="width: 460px;">
              <el-select v-model="formData.customer_id" placeholder="Select Customer" style="width:300px;">
                <el-option v-for="item in customers" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item> -->

          <el-col :span="7">
            <el-form-item label="Customer PO Number" prop="customernumber" style="width: 460px;">

              <el-select v-model="formData.customernumber" placeholder="Select Number" clearable filterable
                style="width:290px;">
                <el-option v-for="item in quotationlist" :key="item.id" :label="item.ordernumber"
                  :value="item.ordernumber">
                </el-option>
              </el-select>


            </el-form-item>
          </el-col>
          <el-col :span="7">


            <el-form-item label="Create Date" prop="created_at" style="width:460px">
              <el-date-picker v-model="formData.addtime" @input="handleDateChange" type="date" style="width:290px;"
                value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>

          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="Billing Title" prop="billingtitle" style="width: 460px;">
              <el-select v-model="formData.billingtitle" placeholder="Select Title" filterable style="width:290px;"
                @change="changebt">
                <el-option v-for="item in billingtitle" :key="item.id" :label="item.title" :value="item.title">
                </el-option>
              </el-select>

            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="Delivery Title" prop="deliverytitle" style="width: 460px;">
              <el-select v-model="formData.deliverytitle" placeholder="Select Title" filterable style="width:290px;"
                @change="changedt">
                <el-option v-for="item in deliverytitle" :key="item.id" :label="item.title" :value="item.title">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="File" prop="certificates" style="width: 460px;">

              <div v-if="isdiable" style="position: relative;">
                <a v-if="formData.certificates" style="font-size: 12px;" :href="formData.certificates"
                  target="_blank"><img src="../../../assets/pdf.png" style="width: 40px;height: 40px" />
                </a>
                <i v-else class="el-icon-upload"> upload files </i>
              </div>

              <div v-else style="position: relative;">
                <el-upload ref="uploadAvatar" class="avatar-uploader" action="#" :show-file-list="false"
                  :on-change="changeAvatar" :auto-upload="true" :http-request="vgetUploadHandler()" name="file"
                  :limit="1">
                  <img v-if="formData.certificates" src="../../../assets/pdf.png" style="width: 40px;height: 40px" />
                  <i v-else class="el-icon-upload"> upload files </i>
                </el-upload>

                <div v-if="formData.certificates">
                  <a style="font-size: 12px;" :href="formData.certificates" target="_blank">view</a>
                  <span style="font-size: 12px;margin-left: 5px; color: red;" @click="vdelcart()">del</span>
                </div>
              </div>

            </el-form-item>

          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="Billing Attention" prop="billingattention" style="width: 460px;">
              <el-input v-model="formData.billingattention" style="width:290px;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="Delivery Attention" prop="deliveryattention" style="width: 460px;">
              <el-input v-model="formData.deliveryattention" style="width:290px;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="Billing Fax" prop="billingfax" style="width: 460px;">
              <el-input v-model="formData.billingfax" style="width:290px;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="Delivery Fax" prop="deliveryfax" style="width: 460px;">
              <el-input v-model="formData.deliveryfax" style="width:290px;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="Billing Tel" prop="billingtel" style="width: 460px;">
              <el-input v-model="formData.billingtel" style="width:290px;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="Delivery Tel" prop="deliverytel" style="width: 460px;">
              <el-input v-model="formData.deliverytel" style="width:290px;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="Billing Address" prop="billingaddress" style="width: 460px;">
              <el-input v-model="formData.billingaddress" style="width:290px;" :rows="3" type="textarea"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="Delivery Address" prop="deliveryaddress" style="width: 460px;">
              <el-input v-model="formData.deliveryaddress" style="width:290px;" :rows="3" type="textarea"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
          </el-col>
        </el-row>



        <el-form-item class="cadd">
          <div class="table-container">
            <el-table :row-class-name="tableRowClassName" :data="formData.procureditem" prop="procureditem"
              :cell-style="{ 'text-align': 'center' }" :header-cell-style="{ 'text-align': 'center' }" border
              :summary-method="getSummaries" show-summary @mouseleave.native="handleRowMouseLeave"
              v-if="formData.procureditem && formData.procureditem.length > 0">
              <el-table-column label="NO" prop="" width="80">
                <template slot-scope="scope">
                  <div @mouseenter="handleRowMouseEnter(scope.$index)">
                    <span>{{ scope.$index + 1 }}</span>
                    <img v-if="hoveredIndex==scope.$index" src="../../../assets/jiahao.png"
                      style="width: 20px;height: 20px" @click="oncopyproductname(scope.row, scope.$index)" />
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="ProductName" width="150px">
                <template slot-scope="scope">
                  <el-input ref="inputRefs" v-model="scope.row.productname"
                    @input="onChangeproductname(scope.row.productname, scope.$index, $event)" :rows="3"
                    type="textarea"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="SKU" width="150px">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.sku" @input="onChangeproductsku(scope.row.sku, scope.$index, $event)"
                    :rows="3" type="textarea"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="Customer SKU" width="140px">
                <template slot-scope="scope">
                  {{ scope.row.suppliesku }}
                </template>
              </el-table-column>
              <el-table-column label="On hand" width="80px">
                <template slot-scope="scope">
                  {{ scope.row.onhand }}
                </template>
              </el-table-column>
              <el-table-column label="QTY" width="80px">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.qty"
                    @blur="changeqtybatch(scope.row.qty,scope.row.batchbalance,scope.$index)" type="text"
                    oninput="value=value.replace(/[^\d.]/g,'')" />
                </template>
              </el-table-column>
              <el-table-column label="Unit" width="60px">
                <template slot-scope="scope">
                  {{ scope.row.unit}}
                </template>
              </el-table-column>
              <el-table-column label="Customer UOM" width="140px">
                <template slot-scope="scope">
                  {{scope.row.cskuom}}
                </template>
              </el-table-column>
              <el-table-column label="Sale Price" width="100px">
                <template slot-scope="scope">
                <el-input 
                v-model="scope.row.costprice" 
                type="text" 
               @input="handlePriceInput($event, scope.row)"
                />
                </template>
              </el-table-column>
              <el-table-column label="Sale Total" width="100px">
                <template slot-scope="scope">
                  {{ (scope.row.costamount = scope.row.qty * scope.row.costprice).toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column label="Batch Number" width="330px">
                <template slot-scope="scope">
                  <div style="white-space: pre-wrap;width: 100%;">
                    <el-select v-model="scope.row.batchnumber" placeholder="Select Number"
                      @change="changeProduct(scope.$index,$event)" style="white-space: pre-wrap;width: 300px">
                      <el-option v-for="item in scope.row.batchnumberlist" :key="item.batchnumber"
                        :label="itemLabel(item)" :value="item.batchnumber" class="multiline-option"
                        style="white-space: pre-wrap;width: 300px">
                      </el-option>
                    </el-select>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="Note">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.note" :rows="3" type="textarea"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="Actions" width="110" v-if="isNew || (isEdit && !isdiable)">
                <template slot-scope="scope">
                  <el-button plain type="danger" v-permission="['saleorders.destroy']" @click="removeItem(scope.row)"
                    size="mini">delete</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <!--          <div style="text-align: center; font-weight: bold;">
            <span>Total QTY: {{ totalqty }}</span>
            <span> | Total Sale Total: {{ totalamount.toFixed(2) }}</span>
          </div> -->
          <div class="table-container">
            <el-table :data="tableDatav" size="small" stripe border style="width: 100%;display: none;" align="center"
              class="tableDatav" :cell-style="{ 'text-align': 'center' }"
              :header-cell-style="{ 'text-align': 'center' }">
              <el-table-column label="NO" prop="" width="80">
                <template slot-scope="scope">
                  <span>Total</span>
                </template>
              </el-table-column>
              <el-table-column label="ProductName" width="150px">
                <template slot-scope="scope">

                </template>
              </el-table-column>
              <el-table-column label="SKU" width="150px">
                <template slot-scope="scope">

                </template>
              </el-table-column>
              <el-table-column label="Customer SKU" width="140px">
                <template slot-scope="scope">

                </template>
              </el-table-column>
              <el-table-column label="On hand" width="80px">
                <template slot-scope="scope">

                </template>
              </el-table-column>
              <el-table-column label="QTY" width="80px">
                <template slot-scope="scope">
                  {{ totalqty }}
                </template>
              </el-table-column>
              <el-table-column label="Unit" width="60px">
                <template slot-scope="scope">

                </template>
              </el-table-column>
              <el-table-column label="Customer UOM" width="140px">
                <template slot-scope="scope">

                </template>
              </el-table-column>
              <el-table-column label="Sale Price" width="100px">
                <template slot-scope="scope">

                </template>
              </el-table-column>
              <el-table-column label="Sale Total" width="100px">
                <template slot-scope="scope">
                  <span>{{ totalamount.toFixed(2) }}</span>
                </template>
              </el-table-column>


              <el-table-column label="Batch Number" width="330px">
                <template slot-scope="scope">

                </template>
              </el-table-column>

              <el-table-column label="Note">
                <template slot-scope="scope">

                </template>
              </el-table-column>

              <el-table-column label="Actions" width="110" v-if="isNew || (isEdit && !isdiable)">
                <template slot-scope="scope">

                </template>
              </el-table-column>




            </el-table>
          </div>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer" style="margin-left: 170px;" v-if="isNew || (isEdit && !isdiable)">
        <el-button type="primary" @click="addItem" :disabled="isdiable">Add Product</el-button>
        <el-button type="primary" @click="saveHandle('ruleForm')" :disabled="isdiable || isubmit">Submit</el-button>
      </div>
    </div>

    <div class="form plt" v-if="isgoprolist" :style="{ 'top': topx,'left':'600px' }">
      <el-button @click="isgoprolist = false" size="mini"
        style="position: absolute;right: 20px;top: 20px;z-index: 999;height: 40px;color: red;">X</el-button>
      <div class="table">
        <el-table :data="tableData" size="small" stripe border @row-click="handleRowClick" style="width: 100%"
          height="320">
          <el-table-column prop="name" label="Name" width="120" align="center" />
          <el-table-column prop="sku" label="SKU" width="100" />
          <el-table-column label="Spec" width="100" align="center">
            <template v-slot="scope">
              <span>{{ scope.row.uom }}{{ scope.row.uom_sku }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="quantity" min-width="100" />
          <el-table-column prop="packaging" label="Packaging" min-width="100" />
          <el-table-column prop="price" label="Price(S$)" width="100" />
          <el-table-column prop="batchnumber" label="Batch Number" width="160" />
          <el-table-column prop="availableqty" label="Available qty" width="140" />
          <!--          <el-table-column label="Actions" width="200">
            <template slot-scope="scope">
              <el-button plain @click="selectadd(scope.row)">select</el-button>
            </template>
          </el-table-column> -->
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
  import CURD from "@/mixin/CURD";
  import {
    index,
    show,
    update,
    store
  } from "@/api/saleorder";
  import {
    index as adminindex
  } from "@/api/admin";
  import {
    index as billingindex,
  } from "@/api/attention";
  import {
    index as deliveryindex,
  } from "@/api/customeraddre";
  import {
    index as prowarlist
  } from "@/api/inventory";
  import {
    index as warehouselist
  } from "@/api/warehouse";
  import {
    show as quotationlistshow,
    index as quotationlistindex
  } from "@/api/quotationlist";
  import {
    index as skushow
  } from "@/api/suppersku";
  import {
    index as prolist
  } from "@/api/product";
  import {
    store as uploadImg
  } from "@/api/medias";
  import {
    index as superindex
  } from "@/api/supplier";
  import {
    index as customerindex
  } from "@/api/customer";
  export default {
    name: "saleorderadd",
    mixins: [CURD],
    data() {
      return {
        oid: 0,
        isrowindex: null,
        quotationlist: [],
        hoveredIndex: null, // 用于存储当前悬停的行索引
        isubmit: false,
        rowIndex: 0,
        x: 0,
        y: 0,
        topx: '60%',
        isgoprolist: false,
        isdiable: true,
        staff: [{
          id: "KW",
          name: "KW",
        }],
        currency: [{
          id: 1,
          name: "SGD",
        }, {
          id: 2,
          name: "USD",
        }],
        id: null,
        isEdit: false,
        isNew: false,
        formData: {
          staff: "KW",
          procureditem: [],
        },
        module: "saleorder",
        newTitle: "New saleorder",
        editTitle: "Edit saleorder",
        isPaginate: true,
        isUploadFile: false,
        fileReader: new FileReader(),
        isShow: false,
        imageUrl: "",
        customers: [],
        suppliers: [],
        warehouse: [],
        billingtitle: [],
        deliverytitle: [],
        xiabiao: -1,
        tindex: 0,
        tableData: [],
        customersid: [],
        searchForm: {

        },
        isapproved: false,
        inputElements: [],
        tableDatav: [{
          id: "approved",
          name: "approved",
        }],
      };
    },
    watch: {
      'formData.procureditem': {
        handler() {
          //this.updateInputElements();
        },
        deep: true
      }
    },
    computed: {
      totalqty() {
        if (this.formData.procureditem) {
          const totalPrice = this.formData.procureditem.reduce((total, item) => total + parseFloat(item
            .qty), 0);
          return totalPrice ? totalPrice : 0
        }
      },
      totalamount() {
        if (this.formData.procureditem) {
          const amount = this.formData.procureditem.reduce((total, item) => total + parseFloat(item.costamount), 0);
          return amount ? amount : 0
        }
      },
    },
    handlePriceInput(value, row) {
    // 移除非数字和小数点
    value = value.replace(/[^\d.]/g, '');
    
    // 确保只有一个小数点
    if(value.split('.').length > 2) {
      value = value.replace(/\.+$/, '');
    }
    
    // 限制小数点后两位
    if(value.includes('.')) {
      const parts = value.split('.');
      value = parts[0] + '.' + parts[1].slice(0, 2);
    }
    
    // 更新值
    row.costprice = value;
  },
    async created() {

      this.oid = this.$route.query.oid

      if (this.oid > 0) {

        this.isNew = true
        this.isEdit = false
        this.formData.status = "pending"
        this.isdiable = false

        try {
          const {
            data
          } = await quotationlistshow(this.oid);
          console.log(data)
          this.formData = data;

        } catch (error) {
          console.error('Failed to fetch saleordershow:', error);
        }
        console.log("fsdfsdfsdfsd")


        var numStr = "01";
        const {
          data
        } = await index(1, 1);
        var lslist = data;
        if (data.length > 0) {
          var dqskinid = lslist[0].id + 1
          numStr = dqskinid.toString();
        }
        this.isNew = true
        this.formData.status = "pending"
        this.isdiable = false
        const currentDate = new Date();
        const year = currentDate.getFullYear();
        const month = currentDate.getMonth() + 1;
        const day = currentDate.getDate();
        console.log(`${year}-${month}-${day}`);
        this.formData.addtime = `${year}-${month}-${day}`
        this.formData.ordernumber = "SO" + `${year}`.slice(-2) + "-" + numStr.padStart(4, '0')
        //this.addItem()

      } else {

        this.id = this.$route.query.id
        if (this.id > 0) {
          this.isEdit = true
          const {
            data
          } = await show(this.id);
          this.formData = data;
          if (this.formData.status == "approved") {
            this.isapproved = true
          }
          //this.formData.procureditem = data.formdatalist;
        } else {
          var numStr = "01";
          const {
            data
          } = await index(1, 1);
          var lslist = data;
          if (data.length > 0) {
            var dqskinid = lslist[0].id + 1
            numStr = dqskinid.toString();
          }
          this.isNew = true
          this.formData.status = "pending"
          this.isdiable = false
          const currentDate = new Date();
          const year = currentDate.getFullYear();
          const month = currentDate.getMonth() + 1;
          const day = currentDate.getDate();
          console.log(`${year}-${month}-${day}`);
          this.formData.addtime = `${year}-${month}-${day}`
          this.formData.ordernumber = "SO" + `${year}`.slice(-2) + "-" + numStr.padStart(4, '0')
          this.addItem()
          this.$nextTick(() => {
            const inputElement = document.querySelector(`.el-table__row input:nth-child(${1})`);
            if (inputElement) {
              if (inputElement) {
                const inputRect = inputElement.getBoundingClientRect();
                this.y = inputRect.left
                this.x = inputRect.top - 30
                console.log('Input coordinates:', this.x, this.y);
              }
            }
          });
        }


      }
      if (this.oid > 0) {
        try {
          const {
            data
          } = await customerindex(1, 100, {
            name: this.formData.customername
          });
          this.customers = data;
          console.log('ddddddd')
          this.changeterm(this.customers[0].id)
          this.$nextTick(() => {
            this.$forceUpdate()
          })
        } catch (error) {
          console.error('Failed to fetch customer:', error);
        }
      } else {
        try {
          const {
            data
          } = await customerindex(1, 100);
          this.customers = data;
        } catch (error) {
          console.error('Failed to fetch customer:', error);
        }

      }
      try {
        const {
          data
        } = await customerindex(1, 20, {
          cid: 21
        });
        this.customersid = data;
      } catch (error) {
        console.error('Failed to fetch customer:', error);
      }
      try {
        const {
          data
        } = await quotationlistindex(1, 100);
        this.quotationlist = data;
      } catch (error) {
        console.error('Failed to fetch customer:', error);
      }

      try {
        const {
          data
        } = await warehouselist(1, 100);
        this.warehouse = data;
      } catch (error) {
        console.error('Failed to fetch warehouse:', error);
      }



      try {
        const {
          data
        } = await adminindex(1, 100, {
          usertype: 1
        });
        this.staff = data.map(item => ({
          id: item.nickname, // 将 nickname 的值赋给 id
          name: item.nickname // 将 nickname 的值赋给 name
        }));

      } catch (error) {
        console.error('Failed to fetch staff:', error);
      }

    },
    methods: {
      remoteMethod(query) {
        if (query !== '') {
          this.loading = true;
          console.log(query, "dddddddddddddddddddddddd")
          setTimeout(() => {
            this.loading = false;
            try {
              customerindex(1, 100, {
                name: query
              }).then(res => {
                this.customers = res.data
              });
              this.$nextTick(() => {
                this.$forceUpdate()
              })
            } catch (error) {
              console.error('Failed to fetch customer:', error);
            }
          }, 200);
        } else {
          this.customers = [];
        }
      },
      remoteidMethod(query) {
        if (query !== '') {
          this.loading = true;
          console.log(query, "dddddddddddddddddddddddd")
          setTimeout(() => {
            this.loading = false;

            try {
              customerindex(1, 100, {
                customerid: query,
              }).then(res => {
                this.customers = res.data
              });
              this.$nextTick(() => {
                this.$forceUpdate()
              })
            } catch (error) {
              console.error('Failed to fetch customer:', error);
            }
          }, 200);
        } else {
          this.customers = [];
        }
      },
      getSummaries(param) {
        const {
          columns,
          data
        } = param;
        const sums = [];

        columns.forEach((column, index) => {
  if (index === 0) {
    sums[index] = 'Total';
    return;
  }
  if (index === 5) {
    const totalQuantity = data.reduce((sum, row) => {
      return parseFloat((sum + (parseFloat(row.qty) || 0)).toFixed(2));
    }, 0);
    sums[index] = totalQuantity.toFixed(2);
  } else if (index === 9) {
    const totalWeight = data.reduce((sum, row) => {
      return parseFloat((sum + (parseFloat(row.costamount) || 0)).toFixed(2));
    }, 0);
    sums[index] = totalWeight.toFixed(2);
  } else {
    sums[index] = '';
  }
});

        return sums;
      },
      renderHeader(h, data) {
        return h("span", [
          h(
            "el-tooltip", {
              attrs: {
                class: "item",
                effect: "dark",
                content: data.column.label,
                placement: "top",
              },
            },
            [h("span", data.column.label)]
          ),
        ]);
      },
      itemLabel(item) {
        return item.batchnumber + '--EX' + item.expirationdate + '-QTY：' + item.quantity;
      },
      vdelcart() {
        console.log("vdelcartvdelcart")
        this.formData.certificates = ""
        this.$forceUpdate()
      },
      vgetUploadHandler() {
        return (options) => {
          this.uploadHandlev(options);
        };
      },
      async uploadHandlev(options) {
        const file = options.file;
        if (file) {
          this.fileReader.readAsDataURL(file);
        }
        this.fileReader.onload = () => {
          const formData = new FormData();
          formData.append("file", file);
          uploadImg(formData)
            .then((res) => {
              console.log(res)
              var {
                data
              } = res;
              this.$message.success(res.status);
              this.formData.certificates = data.url
              this.$forceUpdate()
            })
            .catch((err) => {
              if (err.response.status === 422) {
                const {
                  info,
                  fileName
                } = err.response.data;
                this.$message.error(info);
              }
            });
        };

      },
      handleRowClick(row) {
        this.selectadd(row);
      },
      handlePriceInput(value, row) {
      // 移除非数字和小数点
      value = value.replace(/[^\d.]/g, '');
      // 确保只有一个小数点
      if(value.split('.').length > 2) {
      value = value.replace(/\.+$/, '');
      }
      // 限制小数点后两位
      if(value.includes('.')) {
      const parts = value.split('.');
      value = parts[0] + '.' + parts[1].slice(0, 2);
      }
      // 更新值
      row.costprice = value;
      },

      changeqtybatch(q, b, index) {
        if (parseInt(q) > parseInt(b)) {
          this.isrowindex = index
        } else {
          this.isrowindex = null
        }
      },
      tableRowClassName({
        row,
        rowIndex
      }) {
        if (rowIndex === this.isrowindex) {
          return 'success-row';
        }
        return '';
      },
      handleremindertimeChange(value) {
        this.formData.remindertime = value
        this.$forceUpdate()
      },
      handleDateChange(value) {
        console.log('Date changed:', value);
        this.formData.addtime = value
        this.$forceUpdate()
      },
      goinvocie() {
        this.$store.dispatch('tagsView/delView', this.$route);
        this.$router.push({
          path: '/saleinvoice/saleinvoiceadd?oid=' + this.id,
        });
      },
      handleRowMouseEnter(v) {
        this.hoveredIndex = v;
      },
      handleRowMouseLeave() {
        this.hoveredIndex = null; // 鼠标离开时重置悬停索引
      },
      oncopyproductname(row, index) {
        this.xiabiao = this.xiabiao + 1
        this.formData.procureditem.push({
          index: this.xiabiao,
          productname: row.productname,
          sku: row.sku,
          suppliesku: row.suppliesku,
          onhand: row.onhand,
          qty: row.qty,
          unit: row.unit,
          cskuom: row.cskuom,
          costprice: row.costprice,
          costamount: row.costamount,
          saleprice: row.saleprice,
          expirationdate: row.expirationdate,
          certificates: row.certificates,
          batchnumber: row.batchnumber,
          batchnumberlist: row.batchnumberlist,
          note: row.note,
          product_id: row.product_id,
          batchbalance: row.batchbalance,
          expirydate: row.expirydate
        });
        console.log(this.formData.procureditem, "psss")
      },
      async changeterm(value) {
        const selectedTerm = this.customers.find(item => item.id === value);
        if (selectedTerm) {

          this.$set(this.formData, 'creditterm', selectedTerm.crediterm || '')
          this.$set(this.formData, 'currency', selectedTerm.currency || '')
          this.$set(this.formData, 'customercredit', selectedTerm.creditlimit || '')

          this.$nextTick(() => {
            this.$forceUpdate()
          })
          try {
            var {
              data
            } = await billingindex(1, 100, {
              customer_id: value,
              type: 1
            });
            this.billingtitle = data
            if (this.billingtitle.length > 0) {

              this.$set(this.formData, 'billingtitle', this.billingtitle[0].title || '')
              this.$set(this.formData, 'billingattention', this.billingtitle[0].attention || '')
              this.$set(this.formData, 'billingfax', this.billingtitle[0].fax || '')
              this.$set(this.formData, 'billingtel', this.billingtitle[0].tel || '')
              this.$set(this.formData, 'billingaddress', this.billingtitle[0].address || '')

              this.$nextTick(() => {
                this.$forceUpdate()
              })
            } else {
              this.$set(this.formData, 'billingtitle', '')
              this.$set(this.formData, 'billingattention', "")
              this.$set(this.formData, 'billingfax', '')
              this.$set(this.formData, 'billingtel', "")
              this.$set(this.formData, 'billingaddress', '')
            }
            var {
              data
            } = await deliveryindex(1, 100, {
              customer_id: value,
              type: 1
            });
            this.deliverytitle = data
            if (this.deliverytitle.length > 0) {

              this.$set(this.formData, 'deliverytitle', this.deliverytitle[0].title || '')
              this.$set(this.formData, 'deliveryattention', this.deliverytitle[0].attention || '')
              this.$set(this.formData, 'deliveryfax', this.deliverytitle[0].fax || '')
              this.$set(this.formData, 'deliverytel', this.deliverytitle[0].tel || '')
              this.$set(this.formData, 'deliveryaddress', this.deliverytitle[0].address || '')

              this.$nextTick(() => {
                this.$forceUpdate()
              })
            } else {

              this.$set(this.formData, 'deliverytitle', '')
              this.$set(this.formData, 'deliveryattention', "")
              this.$set(this.formData, 'deliveryfax', '')
              this.$set(this.formData, 'deliverytel', "")
              this.$set(this.formData, 'deliveryaddress', '')
            }
          } catch (error) {
            console.error('Failed to fetch customer:', error);
          }

        }
      },
      changebt(value) {
        const selectedbt = this.billingtitle.find(item => item.title === value);
        if (selectedbt) {
          this.$set(this.formData, 'billingattention', selectedbt.attention || '')
          this.$set(this.formData, 'billingfax', selectedbt.fax || '')
          this.$set(this.formData, 'billingtel', selectedbt.tel || '')
          this.$set(this.formData, 'billingaddress', selectedbt.address || '')

        } else {
          this.$set(this.formData, 'billingattention', '')
          this.$set(this.formData, 'billingfax', "")
          this.$set(this.formData, 'billingtel', '')
          this.$set(this.formData, 'billingaddress', "")
        }
        this.$forceUpdate()
      },
      changedt(value) {
        const selecteddt = this.deliverytitle.find(item => item.title === value);
        if (selecteddt) {

          this.$set(this.formData, 'deliveryattention', selectedbt.attention || '')
          this.$set(this.formData, 'deliveryfax', selectedbt.fax || '')
          this.$set(this.formData, 'deliverytel', selectedbt.tel || '')
          this.$set(this.formData, 'deliveryaddress', selectedbt.address || '')
        } else {
          this.$set(this.formData, 'deliveryattention', "")
          this.$set(this.formData, 'deliveryfax', '')
          this.$set(this.formData, 'deliverytel', "")
          this.$set(this.formData, 'deliveryaddress', '')
        }
        this.$forceUpdate()
      },
      showButton(index) {
        if (isdiable || isapproved) {
          return
        }
        this.hoveredIndex = index; // 设置当前鼠标悬停的行的索引
      },
      hideButton(index) {
        if (isdiable) {
          return
        }
        if (this.hoveredIndex === index) {
          this.hoveredIndex = null; // 清除当前鼠标悬停的行的索引
        }
        // 注意：这里其实不需要传入 index，因为 mouseleave 事件已经足够判断鼠标离开了当前元素
        // 但为了保持与 showButton 方法参数的一致性，这里还是传入了 index（尽管未使用）
      },
      delcart(index) {
        this.formData.procureditem[index].certificates = null
      },
      getUploadHandler(index) {
        // 返回一个函数，该函数将作为 http-request 的处理器
        return (options) => {
          // 在这里，我们可以安全地使用 index，因为它是在这个闭包中捕获的
          this.rowIndex = index; // 如果需要在 uploadHandle 中使用，可以临时存储到组件的 data 或 properties 中
          this.uploadHandle(options);
        };
      },
      async uploadHandle(options) {
        const file = options.file;
        if (file) {
          this.fileReader.readAsDataURL(file);
        }
        this.fileReader.onload = () => {
          const formData = new FormData();
          formData.append("file", file);
          uploadImg(formData)
            .then((res) => {
              console.log(res)
              var {
                data
              } = res;
              this.$message.success(res.status);
              this.formData.procureditem[this.rowIndex].certificates = data.url
            })
            .catch((err) => {
              if (err.response.status === 422) {
                const {
                  info,
                  fileName
                } = err.response.data;
                this.$message.error(info);
              }
            });
        };

      },
      godisable() {
        this.isdiable = !this.isdiable
      },
      addItem() { //增加行
        this.xiabiao += 1
        this.formData.procureditem.push({
          index: this.xiabiao,
          productname: "",
          sku: "",
          suppliesku: "",
          onhand: "",
          qty: "",
          unit: "",
          cskuom: "",
          costprice: "",
          costamount: "",
          saleprice: "",
          expirationdate: "",
          certificates: "",
          batchnumber: "",
          note: "",
          product_id: "",
          batchbalance: "",
          expirydate: ""
        });
      },
      removeItem(row) {
        const index = this.formData.procureditem.indexOf(row)
        if (this.formData.procureditem.length > 1) {
          this.formData.procureditem.splice(index, 1);
        } else {
          this.$message.error("Keep at least one row of data!")
        }
      },
      async editstatus(id, statusdata) {
        console.log(id)
        try {
          await this.$confirm("This operation will permanently Save status. Do you want to continue?", "prompt", {
            confirmButtonText: "Confirm",
            cancelButtonText: "Cancel",
            type: "warning"
          });
          let {
            info
          } = await update({
            id: id,
            action: "status",
            status: statusdata
          });
          this.$message.success("Status update successful");
          this.isapproved = true

          // 刷新当前页
          const {
            data
          } = await show(this.id);
          this.formData = data;
          if (this.formData.status == "approved") {
            this.isapproved = true
          }
          if (this.formData.status == "rejection") {
            this.isapproved = false
            this.isdiable = true
            this.formData.status == "rejection"
          }
        } catch (error) {
          this.$message({
            type: "info",
            message: "Cancelled save"
          });
        }
      },
      selectadd(row) {
        if (row) {
          skushow(1, 1, {
            product_id: row.id,
            customer_id: this.formData.customer_id
          }).then(res => {
            if (res.data) {

              this.formData.procureditem[this.tindex].cskuom = res.data[0].cskuom
              this.formData.procureditem[this.tindex].suppliesku = res.data[0].csku
            } else {
              this.formData.procureditem[this.tindex].suppliesku = row.customersku
              this.formData.procureditem[this.tindex].cskuom = row.cskuom
            }
          });
          this.formData.procureditem[this.tindex].productname = row.name
          this.formData.procureditem[this.tindex].qty = 0
          this.formData.procureditem[this.tindex].sku = row.sku
          this.formData.procureditem[this.tindex].onhand = row.availableqty
          this.formData.procureditem[this.tindex].cskuom = row.cskuom
          this.formData.procureditem[this.tindex].unit = row.uom_sku
          this.formData.procureditem[this.tindex].costprice = row.price
          this.formData.procureditem[this.tindex].product_id = row.id
          this.formData.procureditem[this.tindex].batchnumberlist = row.batchnumberlist
          this.formData.procureditem[this.tindex].batchnumber = row.batchnumber

          if (row.batchnumberlist.length > 0) {
            this.formData.procureditem[this.tindex].batchnumber = row.batchnumberlist[0]
              .batchnumber
            this.formData.procureditem[this.tindex].batchbalance = row.batchnumberlist[0]
              .quantity
            this.formData.procureditem[this.tindex].expirationdate = row.batchnumberlist[0]
              .expirationdate
          } else {

          }

          this.isgoprolist = false;
        }
      },
      changeProduct(index, event) {
        for (var i = 0; i < this.formData.procureditem[index].batchnumberlist.length; i++) {
          var tm = this.formData.procureditem[index].batchnumberlist[i].batchnumber
          if (tm == this.formData.procureditem[index].batchnumber) {
            this.formData.procureditem[index].batchbalance = this.formData.procureditem[index].batchnumberlist[i]
              .quantity
            break;
          }
        }
      },
      onChangeproductname(proname, index, event) {
        console.log(index)
        this.$nextTick(() => {
          this.topx = this.x + "px";
          console.log('Input coordinates:', this.x, this.y);
        });
        if (proname) {

          if (this.formData.staff) {
            warehouselist(1, 1, {
              belongingsales: this.formData.staff,
            }).then(res => {
              if (res.data) {
                this.tindex = index
                prowarlist(1, 10000, {
                  name: proname,
                  warehouse_id: res.data[0].id
                }).then(res => {
                  this.tableData = res.data
                  this.isgoprolist = true;
                });
              }
            });
          }
        }
      },
      onChangeproductsku(sku, index, event) {
        console.log(index)
        this.$nextTick(() => {
          this.topx = this.x + "px";
          console.log('Input coordinates:', this.x, this.y);
        });
        if (sku) {
          if (this.formData.staff) {
            warehouselist(1, 1, {
              belongingsales: this.formData.staff,
            }).then(res => {
              if (res.data) {
                this.tindex = index
                prowarlist(1, 10000, {
                  sku: sku,
                  warehouse_id: res.data[0].id
                }).then(res => {
                  this.tableData = res.data
                  this.isgoprolist = true;
                });
              }
            });
          }
        }
      },
      checkDataAndGetPosition(inputElement) {
        if (inputElement.value === '') {
          setTimeout(() => {
            this.checkDataAndGetPosition(inputElement);
          }, 1000); // 等待1秒后再次尝试获取数据
        } else {
          const inputRect = inputElement.getBoundingClientRect();
          const inputCoordinates = {
            x: inputRect.left,
            y: inputRect.top
          };
          console.log('Input coordinates:', inputCoordinates);
        }
      },
      handleClick(tab, event) {
        console.log(tab, event);
      },
      edit(id) {
        this.$router.push({
          path: '/product/editproduct',
          query: {
            id: id
          }
        })
      },
      onOpen(id) { // 展开
        this.currentOpen = id;
      },
      onClose(id) { // 关闭
        if (this.currentOpen === id) {
          this.currentOpen = null;
        }
      },
      async saveOrder(row) {
        let data = {
          id: row.id,
          order: row.order,
          action: "order"
        };
        row.isEdit = false;
        let {
          info
        } = await update(data);
        this.fetchData();
      },
      transfromData(data) {
        let result = data.map((item) => {
          item.isEdit = false;
          return item;
        });
        return result;
      },
      saveHandle(form) {
        this.save(form);
      },
      close() {
        this.$router.push({
          path: '/salemodel/saleorder'
        });
      },
      async save(form) {
        this.$refs[form].validate(async (valid) => {
          if (valid) {
            try {
              this.isubmit = true
              for (var i = 0; i < this.formData.procureditem.length; i++) {
                var tm = this.formData.procureditem[i].productname
                if (tm == "") {
                  this.$message.error("Please add a product data");
                  this.isubmit = false
                  return false
                }
                var tm = this.formData.procureditem[i].qty
                if (tm == "") {
                  this.$message.error("Please add a product qty");
                  this.isubmit = false
                  return false
                }
                var tm = this.formData.procureditem[i].costprice
                if (tm == "") {
                  this.$message.error("Please add a product saleprice");
                  this.isubmit = false
                  return false
                }
                var tm = this.formData.procureditem[i].expirationdate
                if (tm == "") {
                  this.$message.error("Please add a product expirationdate");
                  this.isubmit = false
                  return false
                }
                var tm = this.formData.procureditem[i].batchnumber
                if (tm == "") {
                  this.$message.error("Please add a product batchnumber");
                  this.isubmit = false
                  return false
                }
              }

              this.formData.totalqty = this.totalqty
              this.formData.totalamount = this.totalamount
              for (var i = 0; i < this.customers.length; i++) {
                if (this.formData.customer_id == this.customers[i].id) {
                  this.formData.customername = this.customers[i].name
                }
              }
              // for (var i = 0; i < this.suppliers.length; i++) {
              //   if (this.formData.supplier_id == this.suppliers[i].id) {
              //     this.formData.suppliername = this.suppliers[i].name
              //     break
              //   }
              // }

              if (this.isEdit) {
                let {
                  update
                } = require(`@/api/${this.module}`);
                let {
                  info
                } = await update(this.formData);
                this.$message.success("Edit successfully");
                setTimeout(() => {
                  this.$store.dispatch('tagsView/delView', this.$route);
                  this.$router.push({
                    path: '/salemodel/saleorder'
                  });
                }, 1000);
              }
              if (this.isNew) {
                if (this.formData.procureditem != null && this.formData.procureditem.length > 0) {

                } else {
                  this.$message.error("Please add a product");
                  return false
                }
                let {
                  store
                } = require(`@/api/${this.module}`);
                let info1 = await store(this.formData);
                if (info1) {
                  if (info1.status_code = 201) {
                    this.$message.success("Add successfully");
                    setTimeout(() => {
                      this.$store.dispatch('tagsView/delView', this.$route);
                      this.$router.push({
                        path: '/saleorder/editsaleorder',
                        query: {
                          id: info1.info
                        }
                      })
                    }, 1000);
                  } else {
                    this.isubmit = false
                    this.$message.error("Data verification error");
                    return false;
                  }
                }

              }
              this.fetchData();
              this.isEdit = false;
              this.isNew = false;
              this.isubmit = false
              this.dialogFormVisible = false;
            } catch (error) {
              let result = error.response.data;
              this.$message.error(result.info);
            }
          } else {
            this.isubmit = false
            this.$message.error("Data verification error, please input according to the specified rules");
            return false;
          }
        });
      },
      async avatarUpload(options) {
        const file = options.file;
        if (file) {
          this.fileReader.readAsDataURL(file);
        }
        this.fileReader.onload = async () => {
          const formData = new FormData();
          formData.append("file", file);
          uploadImg(formData)
            .then((res) => {
              const {
                data
              } = res;
              this.formData.image = data.url;
              //this.save("ruleForm");
            })
            .catch((err) => {
              options.onError(err);
            });
        };
      },
      changeAvatar(file, fileList) {
        console.log("sssssssssssssssssss")
        const reader = new window.FileReader();
        reader.readAsDataURL(new Blob([file.raw]));
        reader.onload = (e) => {
          this.formData.image = reader.result;
          this.imageUrl = reader.result;
          this.isUploadFile = true;
          console.log(reader.result)
        };
      },
      async changeStatus(row) {
        let tips = "";
        if (row.status) {
          tips = "是否启用该文章?";
        } else {
          tips = "是否禁用该文章?";
        }
        this.$confirm(tips, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(async () => {
            let data = {
              id: row.id,
              status: row.status,
              action: "status"
            };
            let {
              info
            } = await update(data);
            this.$message.success(info);
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "Cancelled deletion"
            });
          });
      }

    }
  }
</script>
<style>
  .custom-dropdown {
    max-width: 300px;
    /* 设置最大宽度，根据需要调整 */
  }

  .table-container {
    width: 100%;
    overflow-x: auto;
  }

  .custom-dropdown .el-select-dropdown {
    white-space: normal;
    /* 允许换行 */
  }

  .custom-dropdown .el-option {
    white-space: normal;
    /* 允许换行 */
    word-wrap: break-word;
    /* 允许长单词换行 */
  }
</style>
<style>
  /* 你可以在这里添加样式来突出显示悬停的行，如果需要的话 */
  .el-table .el-table__row--hover {
    background-color: red;
  }

  /* 在您的样式表中添加以下样式 */
  .multiline-option {
    white-space: normal;
  }

  .el-table .success-row {
    background: #fb5c5c !important;
  }

  .avatar-uploader {
    position: relative;
  }

  .customWidth {
    width: 80%;
  }

  .tableDatav .has-gutter {
    display: none;
  }

  .cadd {
    width: 100%;
  }

  .plt {
    position: absolute;
    z-index: 9999;
    left: 170px;
    background-color: #f5f5f5;
  }

  #cadd .el-table th.el-table__cell>.cell {
    display: inline-block;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    position: relative;
    vertical-align: middle;
    padding-left: 10px;
    padding-right: 10px;
    width: 100%;
    font-weight: 600 !important;
    color: #000;
    font-size: 14px !important;
  }
</style>
<style>
  .warpper {
    padding: 30px 20px;
    color: #606266;
    font-size: 14px;
    word-break: break-all;
  }

  .table,
  .toolbar,
  .page {
    margin: 20px;
  }

  .toolbar {
    margin-top: 10px;
    padding: 5px;
  }

  .table {
    margin-bottom: 10px;
  }

  .page {
    margin-top: 10px;
    text-align: center;
  }

  .green-text {
    color: green;
  }

  .red-text {
    color: red;
  }

  .yellow-text {
    color: yellow;
  }
</style>